package jaux.tank.api.controller.system;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;
import jaux.tank.api.controller.BaseController;
import jaux.tank.bean.annotion.core.BussinessLog;
import jaux.tank.bean.entity.system.Dict;
import jaux.tank.bean.enumeration.BizExceptionEnum;
import jaux.tank.bean.exception.TankException;
import jaux.tank.bean.vo.front.Ret;
import jaux.tank.bean.vo.front.Rets;
import jaux.tank.dao.system.DictRepository;
import jaux.tank.service.system.DictService;
import jaux.tank.utils.BeanUtil;
import jaux.tank.utils.StringUtils;
import jaux.tank.utils.ToolUtil;
import jaux.tank.warpper.DictWarpper;

/**
 * DictController
 *
 * @author zt
 * @version 2018/11/17 0017
 */
@RestController("dictApiController")
@RequestMapping("/api/dict")
public class DictController extends BaseController {
    @Autowired
    private DictRepository dictRepository;
    @Autowired
    private DictService dictService;

    /**
     * 获取所有字典列表
     */
    @ApiOperation(value = "查询字典列表")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public Ret<Object> list(String name) {
        if(StringUtils.isNotEmpty(name)){
            List<Dict> list = dictRepository.findByNameLike(name);
            return Rets.success(new DictWarpper(BeanUtil.objectsToMaps(list)).warp());
        }
        List<Dict> list = dictRepository.findByPidIsNull();
        return Rets.success(new DictWarpper(BeanUtil.objectsToMaps(list)).warp());
    }

    @ApiOperation(value = "增加字典")
    @RequestMapping(method = RequestMethod.POST)
    @BussinessLog(value = "添加字典", key = "dictName")
    public Ret<Object> add(String dictName, String dictValues) {
        if (ToolUtil.isOneEmpty(dictName, dictValues)) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        this.dictService.addDict(dictName, dictValues);
        return Rets.success();
    }

    @ApiOperation(value = "修改字典")
    @RequestMapping(method = RequestMethod.PUT)
    @BussinessLog(value = "修改字典", key = "dictName")
    public Ret<Object> update(String id,String dictName, String dictValues) {
        if (ToolUtil.isOneEmpty(dictName, dictValues)) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        this.dictService.editDict(id,dictName, dictValues);
        return Rets.success();
    }

    @ApiOperation(value = "删除字典")
    @RequestMapping(method = RequestMethod.DELETE)
    @BussinessLog(value = "删除字典", key = "id")
    public Ret<Object> delete(@RequestParam String id) {
        this.dictService.delteDict(id);
        return Rets.success();
    }

}
